package main

import (
	"errors"
	"fmt"
	"github.com/afex/hystrix-go/hystrix"
	"math/rand"
	"time"
)

func main() {

	configA := hystrix.CommandConfig{
		Timeout:               2000,
		MaxConcurrentRequests: 3,
		// 满足这两个参数后，不在延迟，直接执行降级方法
		RequestVolumeThreshold: 5,  // 请求阈值
		ErrorPercentThreshold:  20, // 错误百分比
	}

	hystrix.ConfigureCommand("get_prod", configA)
	circuit, _, _ := hystrix.GetCircuit("get_prod")

	for true {
		err := hystrix.Do("get_prod", func() error {
			p := getProduct()
			fmt.Println(p)
			return nil
		}, func(err error) error {
			fmt.Println("callback")
			return errors.New("time out")
		})

		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(circuit.IsOpen())

		time.Sleep(time.Second)
	}

}

func getProduct() int {

	r := rand.Intn(10)
	if r < 6 {
		time.Sleep(time.Second * 2)
	}
	return r
}
